package com.rocker.graduation.job;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.rocker.graduation.dao.OrdersMapper;
import com.rocker.graduation.dao.StatusMapper;
import com.rocker.graduation.domain.Orders;
import com.rocker.graduation.domain.Status;

@Component
public class OrderTask {

	@Autowired
	private OrdersMapper ordersMapper;
	
	@Autowired
	private StatusMapper statusMapper;
	
	private static final Logger logger = Logger.getLogger(OrderTask.class);
	
	@Scheduled(cron="0 0 0 * * ?")
	public void cancelOrder(){
		logger.info("Cancel overdue order started.");
		List<Orders> orderList = ordersMapper.getOverdueOrders();
		if (!CollectionUtils.isEmpty(orderList)) {
			for (Orders orders : orderList) {
				Date now = ordersMapper.getSysDate();
				orders.setOrderStatus(0);
				orders.setModifyDate(now);
				int i = ordersMapper.updateByPrimaryKeySelective(orders);
				if (i > 0) {
					Status status = new Status();
					status.setOrderId(orders.getOrderId());
					status.setOrderStatus(0);
					status.setModifyDate(now);
					statusMapper.insertSelective(status);
				}
			}
		}
		logger.info("Cancel overdue order ended.");
		logger.info("Now is " + ordersMapper.getSysDate());
	}
	
	@Scheduled(cron="0 0 0 * * ?")
	public void completeOrder(){
		logger.info("Complete overdue order started.");
		List<Orders> orderList = ordersMapper.getPendingOrders();
		if (!CollectionUtils.isEmpty(orderList)) {
			for (Orders orders : orderList) {
				Date now = ordersMapper.getSysDate();
				orders.setOrderStatus(5);
				orders.setModifyDate(now);
				int i = ordersMapper.updateByPrimaryKeySelective(orders);
				if (i > 0) {
					Status status = new Status();
					status.setOrderId(orders.getOrderId());
					status.setOrderStatus(5);
					status.setModifyDate(now);
					statusMapper.insertSelective(status);
				}
			}
		}
		logger.info("Complete overdue order ended.");
		logger.info("Now is " + ordersMapper.getSysDate());
	}
	
	@Scheduled(cron="0 0/5 * * * ?")
	public void test(){
		System.out.println(new Date());
		logger.info("This is a info message!");
	}
}
